package io.kiki.sba.registry.server.metadata.lease.impl;

import io.kiki.sba.registry.common.model.Node;
import io.kiki.sba.registry.common.model.metaserver.Lease;
import io.kiki.sba.registry.common.model.metaserver.cluster.VersionedList;
import io.kiki.sba.registry.server.metadata.lease.LeaseFilter;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;


public abstract class AbstractEvictableFilterableLeaseManager<T extends Node> extends AbstractEvictableLeaseManager<T> {

    @Autowired
    private List<LeaseFilter> leaseFilterList;

    @Override
    public VersionedList<Lease<T>> VersionedLeaseList() {
        if (leaseFilterList == null || leaseFilterList.isEmpty()) {
            return super.VersionedLeaseList();
        }
        VersionedList<Lease<T>> rawVersionedList = super.VersionedLeaseList();
        List<Lease<T>> leaseList = rawVersionedList.getList();
        for (LeaseFilter leaseFilter : leaseFilterList) {
            leaseList = filter(leaseList, leaseFilter);
        }
        return new VersionedList<>(leaseList, rawVersionedList.getEpoch());
    }

    protected List<Lease<T>> filter(List<Lease<T>> leaseList, LeaseFilter leaseFilter) {
        List<Lease<T>> list = new ArrayList<>(leaseList.size());
        for (Lease<T> lease : leaseList) {
            if (leaseFilter.allowSelect(lease)) {
                list.add(lease);
            }
        }
        return list;
    }


}
